package org.grow.support.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

/**
 * @Author: xwg
 * @CreateDate: 2022/5/27
 */

@RestController
@RequestMapping("/support/util")
public class UtilController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/codeGene")
    public String codeGene(@RequestParam("prefix") String prefix) {
//        SH202205271433320001
//        SH202205271434320002
//        yyyyMMddHHmmss
//        if (prefix.length()!=2){
//            prefix.substring(0,2);
//        }
        prefix = prefix.toUpperCase(Locale.ROOT);
        LocalDateTime now = LocalDateTime.now();
        String ss = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
//        System.out.println(ss);
//        System.out.println(prefix);
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
//        仅当不存在code情况下 第一次初始化为1
        String targetKey = "CODE:" + prefix;
        ops.setIfAbsent(targetKey, String.valueOf(1));
        String currentCode = ops.get(targetKey);
        ops.increment(targetKey);
//        System.out.println("redis 存储的数据是 " + currentCode);
        String finalCode = null;
        int i = Integer.parseInt(currentCode);
        if (i >= 10000) {
            finalCode = (i % 10000) + "";
        } else {
            finalCode = String.format("%04d", i);
        }
//        System.out.println("格式化数字：" + finalCode);

        return prefix + ss + finalCode;
    }
}
